Test Setup Failed
Push — master ( 51607c...6b8ca8 )
by Paul
03:43
created

GLSR.parseFormData   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 57
rs 8.7433

1 Function

Rating   Name   Duplication   Size   Complexity  
C 0 38 12

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
var GLSR = {};
2
3
GLSR.addClass = function( el, className ) {
4
	if( el.classList ) {
5
		el.classList.add( className );
6
	}
7
	else if( !GLSR.hasClass( el, className )) {
8
		el.className += ' ' + className;
9
	}
10
};
11
12
GLSR.convertValue = function( value ) {
13
	if( GLSR.isNumeric( value )) {
14
		return parseFloat( value );
15
	}
16
	else if( value === 'true') {
17
		return true;
18
	}
19
	else if( value === 'false' ) {
20
		return false;
21
	}
22
	else if( value === '' || value === null ) {
23
		return undefined;
24
	}
25
	return value;
26
};
27
28
GLSR.getAjax = function( url, success ) {
29
	var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' );
0 ignored issues
show
Bug introduced by
The variable XMLHttpRequest seems to be never declared. If this is a global, consider adding a /** global: XMLHttpRequest */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
30
	xhr.open( 'GET', url );
31
	xhr.onreadystatechange = function() {
32
		if( xhr.readyState > 3 && xhr.status === 200 ) {
33
			success( xhr.responseText );
34
		}
35
	};
36
	xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
37
	xhr.send();
38
	return xhr;
39
};
40
41
GLSR.hasClass = function( el, className ) {
42
	if( el.classList ) {
43
		return el.classList.contains( className );
44
	}
45
	return new RegExp( '\\b' + className + '\\b' ).test( el.className );
46
};
47
48
GLSR.inArray = function( needle, haystack ) {
49
	var length = haystack.length;
50
	while( length-- ) {
51
		if( haystack[ length ] === needle ) {
52
			return true;
53
		}
54
	}
55
	return false;
56
};
57
58
GLSR.isNumeric = function( value ) {
59
	return !( isNaN( parseFloat( value )) || !isFinite( value ));
60
};
61
62
GLSR.isString = function( str ) {
63
	return Object.prototype.toString.call( str ) === '[object String]';
64
};
65
66
GLSR.on = function( type, el, handler ) {
67
	if( GLSR.isString( el )) {
68
		el = document.querySelectorAll( el );
69
	}
70
	[].forEach.call( el, function( node ) {
71
		node.addEventListener( type, handler );
72
	});
73
};
74
75
GLSR.off = function( type, el, handler ) {
76
	if( GLSR.isString( el )) {
77
		el = document.querySelectorAll( el );
78
	}
79
	[].forEach.call( el, function( node ) {
80
		node.removeEventListener( type, handler );
81
	});
82
};
83
84
/**
85
 * Adapted from https://github.com/bitovi/jquerypp/blob/master/dom/form_params/form_params.js
86
 */
87
GLSR.parseFormData = function( form, convert ) {
88
	convert = !!convert || false;
89
	var keyBreaker = /[^\[\]]+/g; // used to parse bracket notation
90
	var data = {};
91
	var seen = {}; // used to uniquely track seen values
92
	var nestData = function( field, data, parts, seenName )
93
	{
94
		var name = parts.shift();
95
		// Keep track of the dot separated fullname
96
		seenName = seenName ? seenName + '.' + name : name;
97
		if( parts.length ) {
98
			if( !data[ name ] ) {
99
				data[ name ] = {};
100
			}
101
			// Recursive call
102
			nestData( field, data[ name ], parts, seenName );
103
		}
104
		else {
105
			// Convert the value
106
			var value = convert ? GLSR.convertValue( field.value ) : field.value;
107
			// Handle same name case, as well as "last checkbox checked" case
108
			if( seenName in seen && field.type !== 'radio' && !data[ name ].isArray()) {
109
				if( name in data ) {
110
					data[ name ] = [ data[name] ];
111
				}
112
				else {
113
					data[ name ] = [];
114
				}
115
			}
116
			else {
117
				seen[ seenName ] = true;
118
			}
119
			// Finally, assign data
120
			if( GLSR.inArray( field.type, ['radio','checkbox'] ) && !field.checked )return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
121
122
			if( !data[ name ] ) {
123
				data[ name ] = value;
124
			}
125
			else {
126
				data[ name ].push( value );
127
			}
128
		}
129
	};
130
131
	for( var i = 0; i < form.length; i++ ) {
132
		var field = form[i];
133
		if( !field.name || field.disabled || GLSR.inArray( field.type, [
134
			'file','reset','submit','button',
135
		]))continue;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
136
		var parts = field.name.match( keyBreaker );
137
		if( !parts.length ) {
138
			parts = [ field.name ];
139
		}
140
		nestData( field, data, parts );
141
	}
142
	return data;
143
};
144
145
GLSR.postAjax = function( url, data, success ) {
146
	var params = typeof data !== 'string' ? GLSR.serialize( data ) : data;
147
	var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' );
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable XMLHttpRequest seems to be never declared. If this is a global, consider adding a /** global: XMLHttpRequest */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
148
	xhr.open( 'POST', url ); // asynchronously
149
	xhr.onreadystatechange = function() {
150
		if( xhr.readyState > 3 && xhr.status === 200 ) {
151
			success( JSON.parse( xhr.responseText ));
152
		}
153
	};
154
	xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
155
	xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' );
156
	xhr.send( params );
157
	return xhr;
158
};
159
160
GLSR.ready = function( fn ) {
161
	if( typeof fn !== 'function' )return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
162
	// in case the document is already rendered
163
	if( document.readyState !== 'loading' ) {
164
		fn();
165
	}
166
	// modern browsers
167
	else if( document.addEventListener ) {
168
		document.addEventListener( 'DOMContentLoaded', fn );
169
	}
170
	// IE <= 8
171
	else {
172
		document.attachEvent( 'onreadystatechange', function() {
173
			if( document.readyState === 'complete' ) {
174
				fn();
175
			}
176
		});
177
	}
178
};
179
180
GLSR.removeClass = function( el, className ) {
181
	if( el.classList ) {
182
		el.classList.remove( className );
183
	}
184
	else {
185
		el.className = el.className.replace( new RegExp( '\\b' + className + '\\b', 'g' ), '' );
186
	}
187
};
188
189
GLSR.serialize = function( obj, prefix ) {
190
	var str = [];
191
192
	for( var property in obj ) {
193
		if( !obj.hasOwnProperty( property ))continue;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
194
		var key = prefix ? prefix + '[' + property + ']' : property;
195
		var value = obj[ property ];
196
		str.push( typeof value === 'object' ?
197
			GLSR.serialize( value, key ) :
198
			encodeURIComponent( key ) + '=' + encodeURIComponent( value )
199
		);
200
	}
201
	return str.join( '&' );
202
};
203
204
GLSR.toggleClass = function( el, className ) {
205
	if( !GLSR.hasClass( el, className )) GLSR.addClass( el, className );
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
206
	else GLSR.removeClass( el, className );
207
};
208
209
GLSR.insertAfter = function( el, tag, attributes ) {
210
	var newEl = GLSR.createEl( tag, attributes );
211
	el.parentNode.insertBefore( newEl, el.nextSibling );
212
	return newEl;
213
};
214
215
GLSR.appendTo = function( el, tag, attributes ) {
216
	var newEl = GLSR.createEl( tag, attributes );
217
	el.appendChild( newEl );
218
	return newEl;
219
};
220
221
GLSR.createEl = function( tag, attributes ) {
222
	var el = ( typeof tag === 'string' ) ? document.createElement( tag ) : tag;
223
	attributes = attributes || {};
224
	for( var key in attributes ) {
225
		if( !attributes.hasOwnProperty( key ) )continue;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
226
		el.setAttribute( key, attributes[ key ] );
227
	}
228
	return el;
229
};
230